/*
 * Module name : ProductTable
 */
import Mn from 'backbone.marionette';
import Radio from 'backbone.radio';
import ProductView from './ProductView.js';
import ProductEmptyView from './ProductEmptyView.js';

const template = require('./templates/ProductTable.mustache');

const ProductCollectionView = Mn.CollectionView.extend({
    tagName: 'tbody',
    childView: ProductView,
    emptyView: ProductEmptyView,
    collectionEvents: {
        'sync': 'render'
    },
    // Bubble up child view events
    childViewTriggers: {
        'model:delete': 'model:delete',
        'model:duplicate': 'model:duplicate',
        'model:edit': 'model:edit',
        'model:archive': 'model:archive'
    }
});

const ProductTable = Mn.View.extend({
    template: template,
    regions: {
        tbody: {
            el: 'tbody',
            replaceElement: true
        }
    },
    ui: {},
    // Listen to the current's view events
    events: {
        "click .sortable": "sortTable"
    },
    triggers: {
        "navigate:page": "navigate:page"
    },
    // Listen to child view events
    childViewEvents: {},
    // Bubble up child view events
    childViewTriggers: {
        'model:delete': 'model:delete',
        'model:duplicate': 'model:duplicate',
        'model:edit': 'model:edit',
        'model:archive': 'model:archive'
    },
    initialize() {
        this.facade = Radio.channel('facade');
        this.config = Radio.channel('config');
    },
    onRender() {
        this.showChildView('tbody', new ProductCollectionView({
            collection: this.collection,
            childViewOptions: {
                tvaMode: this.config.request('get', 'tva_mode_enabled')
            }
        }));
    },
    sortTable(e) {
        e.preventDefault();

        const $e = $(e.currentTarget);
        const newSortKey = $e.data("sort");
        const isSameSortKey = (this.collection.state.sortKey == newSortKey);
        const isOldOrderAsc = (this.collection.state.order == -1);
        const orderCodes = {
            "asc": -1,
            "desc": 1
        };
        const newOrderCode = (isSameSortKey && isOldOrderAsc) ? orderCodes["desc"] : orderCodes["asc"];

        this.collection.setSorting(newSortKey, newOrderCode);
        this.triggerMethod("navigate:page", this.collection.state.currentPage);
    },
    templateContext() {
        const sortKey = this.collection.state.sortKey;
        const order = (this.collection.state.order == -1) ? "asc" : "desc";
        /*  Description des en-têtes de colonnes pour le "template":
         *   - label: Intitulé de l'en-tête de colonne
         *   - type: "number" ou "text" (valeur par défaut)
         *   - key: Clef de tri pour les colonnes triables
         *   - aria: Libellé ARIA (par défaut: "label" en minuscules)
         */
        let headers = [{
                label: "ID",
                key: "id",
                aria: "identifiant"
            },
            {
                label: "Nom interne",
                key: "label"
            },
            {
                label: "Référence",
                key: "ref"
            },
            {
                label: "Fournisseur",
                key: "supplier_id"
            },
            {
                label: "Réf frns",
                key: "supplier_ref",
                aria: "Référence fournisseur"
            },
            {
                label: "Catégorie"
            },
            {
                label: "Stock",
                type: "number"
            },
            {
                label: "Coût",
                type: "number"
            },
            {
                label: "Prix de vente",
                type: "number",
                key: "ht",
                aria: "prix hors taxes"
            },
            {
                label: "Unité"
            },
            {
                label: "Modifié le",
                key: "updated_at",
                aria: "date de mise à jour"
            },
        ]

        if (this.config.request('get', 'tva_mode_enabled')) {
            headers.push({
                label: "TVA"
            });
        }
        for (let i = 0; i < headers.length; i++) {
            if (headers[i].key) {
                headers[i].isSortable = true;
            }
            if (!headers[i].type) {
                headers[i].type = "text";
            }
            if (!headers[i].aria) {
                headers[i].aria = headers[i].label.toLowerCase();
            }
            if (headers[i].key == sortKey) {
                headers[i].sortClass = " current " + order;
                headers[i].orderIcon = order;
            } else {
                headers[i].sortClass = "";
                headers[i].orderIcon = "arrow";
            }
        }
        let context = {
            colHeaders: headers
        };
        return context;
    }
});
export default ProductTable;